import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/http_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/entity/order/detail/order_detail_entity.dart';
import 'package:distribution_mall_flutter/entity/order/order.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/order/widgets/order_cancel.dart';
import 'package:distribution_mall_flutter/pages/order/widgets/order_more.dart';
import 'package:distribution_mall_flutter/provider/order/common.dart';
import 'package:distribution_mall_flutter/provider/order/order_detail.dart';
import 'package:distribution_mall_flutter/provider/order/order_list.dart';
import 'package:distribution_mall_flutter/router/route_utils.dart';
import 'package:distribution_mall_flutter/router/router.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:webview_flutter/webview_flutter.dart';

class OrderFooter extends ConsumerStatefulWidget {
  final String distributionOrderId;
  const OrderFooter(
      {super.key, required this.distributionOrderId});

  @override
  ConsumerState createState() => _OrderFooter();
}

class _OrderFooter extends ConsumerState<OrderFooter> {
  WebViewController? webViewController;
  String url = '';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      OrderDetailEntity? detail =
          ref.watch(orderDetailProvider.select((value) => value.detal));
      Map<String, dynamic> params = {
        'state': detail?.state,
        'gmtCreate': detail?.gmtCreate,
        'distributionOrderId': widget.distributionOrderId,
        ...Utils.getUserParams()
      };
      url = '${HttpConstant.service}?${Uri(queryParameters: params).query}';
      if (!kIsWeb) {
        webViewController = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..loadRequest(Uri.parse(url))
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (int progress) {},
              onPageStarted: (String url) {},
              onPageFinished: (String url) {},
              onHttpError: (HttpResponseError error) {},
              onWebResourceError: (WebResourceError error) {},
              // onNavigationRequest: (NavigationRequest request) {
              //   if (request.url.startsWith('https://www.youtube.com/')) {
              //     return NavigationDecision.prevent;
              //   }
              //   return NavigationDecision.navigate;
              // },
            ),
          )
          ..reload();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final orderModal = ref.watch(orderDetailProvider);
    List<SaleReasonEntity> list =
        ref.watch(orderCommonProvider.select((value) => value.reasonList));
    return Container(
      height: 60,
      padding: const EdgeInsets.symmetric(horizontal: EdgeConstant.edge20),
      color: Colors.white,
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () {
              Utils.go2Page(() {
                appRouter
                    .push(ServiceRoute(webViewController: webViewController));
              }, suffix: '?distributionOrderId=${widget.distributionOrderId}');
            },
            child: Container(
              padding: const EdgeInsets.all(EdgeConstant.edge5),
              decoration: BoxDecoration(
                  border: Border.all(
                    color: ColorConstant.grey233,
                    width: 0.9,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(5))),
              child: ImageLoader.imageAsset(Assets.assets_icons_service_png,
                  width: 30, height: 30, hasRoot: false),
            ),
          ),
          Wrap(
            alignment: WrapAlignment.end,
            spacing: 5,
            children: [
              Visibility(
                  visible: orderModal.detal?.canCustomerDelete == true,
                  child: OrderMore(
                    arrowDxOffset: -5,
                    distributionOrderId: widget.distributionOrderId,
                    width: 40,
                    goBack: true,
                    callback: () {
                      Future.delayed(const Duration(milliseconds: 500), () {
                        RouteUtils.back();
                      });
                    },
                  )),
              Visibility(
                  visible: orderModal.showTrack,
                  child: CommonBtnWidget.transparentBtn(
                      onPressed: () {
                        if(orderModal.detal?.state != null) {
                          appRouter.push(OrderLogisticsRoute(
                              state: orderModal.detal!.state!,
                              bizOrderNumber: widget.distributionOrderId));
                        }
                      },
                      text: S.of(context).pLogistics,
                      height: 40)),
              // Visibility(
              //     visible: orderModal.showBuyAgain,
              //     child: CommonBtnWidget.transparentBtn(
              //         onPressed: () {},
              //         text: S.of(context).buy_again,
              //         width: 90,
              //         height: 40)),
              Visibility(
                  visible: orderModal.showCancel,
                  child: CommonBtnWidget.transparentBtn(
                      onPressed: () {
                        return EPModalBottomSheet.showCMBS(
                            context: context,
                            builder: (context) => OrderCancel(
                                list: list,
                                onFooterPressed: () {
                                  ref
                                      .read(orderListProvider.notifier)
                                      .refresh({}, false);
                                  RouteUtils.back();
                                },
                                distributionOrderId:
                                    widget.distributionOrderId));
                      },
                      color: ColorConstant.primaryColor,
                      text: S.of(context).cancel,
                      width: 90,
                      height: 40)),
              Visibility(
                  visible: orderModal.showPay,
                  child: CommonBtnWidget.generalBtn(() {
                    appRouter.push(PayListRoute(
                      distributionOrderId: widget.distributionOrderId,
                    ));
                    FirebaseAnalyticsUtils.logEvent(
                        name: PointConstant.orderPay,
                        parameters: {
                          'orderNo': widget.distributionOrderId,
                          'pageName':
                              RouteInfoEnum.getInfo(appRouter.current.name)
                                  .routeZhName
                        });
                  },
                      color: ColorConstant.primaryColor,
                      textStyle: const TextStyle(
                        color: Colors.white,
                        fontSize: FontConstant.f11,
                      ),
                      text: S.current.order_status_to_pay,
                      width: 90,
                      height: 40))
            ],
          )
        ],
      ),
    );
  }
}
